package com.cms.cmsbackend.service;

import com.cms.cmsbackend.mapper.ArticleMapper;
import com.cms.cmsbackend.mapper.CategoryMapper;
import com.cms.cmsbackend.pojo.Article;
import com.cms.cmsbackend.pojo.Category;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

@Service
public class CategoryService {
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private ArticleMapper articleMapper;

    public void save(Category category){
        categoryMapper.insert(category);
    }

    public PageInfo findByPage(int page,int size){
        PageHelper.startPage(page,size);
        List<Category> categories=categoryMapper.selectAll();
        PageInfo pageInfo=new PageInfo<>(categories);
        return pageInfo;
    }

    public void remove(int id){
        //删除栏目需要把栏目下对应的所有的信息都要删除
        //先删除信息，再删除栏目
        Example example=new Example(Article.class);
        example.createCriteria().andEqualTo("category_id",id);
        articleMapper.deleteByExample(example);
        categoryMapper.deleteByPrimaryKey(id);
    }

    public void batchrem(int[] ids){
        for(int id:ids){
            categoryMapper.deleteByPrimaryKey(id);
        }
    }

    public Category choose(int id){
        Category category=categoryMapper.selectByPrimaryKey(id);
        return category;
    }


    public Category upadta(Category category){
        categoryMapper.updateByPrimaryKey(category);
        return category;
    }
}
